import React, { Component, Fragment, PureComponent } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import {
  Button,
  Card,
  Col,
  Divider,
  Form,
  Icon,
  Input,
  message,
  Modal,
  Popconfirm,
  Radio,
  Row,
  Select,
  Spin,
  Tree,
  Switch,
  Badge,
} from 'antd';
import moment from 'moment';
import { saveAs } from 'file-saver';
import ProTable from '@ant-design/pro-table';
import { connect } from 'dva';
import styled from 'styled-components';
import BaseComponent from '@/components/BaseComponent';
import styles from './index.less';
import success from '@/pages/Template/Result/Success';
import AddOrEditView from '@/pages/SystemInit/UserSetting/AddOrEditView';
import CasUserList from '@/pages/SystemInit/UserSetting/CasUserList';

const FormItem = Form.Item;
const { Option } = Select;
const { TreeNode } = Tree;

const LeftLoadingBox = styled.div`
  min-height: 700px;
  display: flex;
  justify-content: center;
  align-items: center;
`;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['error', 'success'];
const status = [
  formatMessage({ id: 'app.common.disable' }),
  formatMessage({ id: 'app.common.able' }),
];

@connect(({ sysUser, loading }) => ({
  sysUser,
  loading: loading.models.sysUser,
  isLoadingLeftTree: loading.effects['sysUser/fetchOrgTree'],
}))
@Form.create()
class UserSetting extends BaseComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    selectedRows: [],
    formValues: {},
    updateFormValues: {},
    roleData: [],
    orgData: [],
    hiddenMenuButton: localStorage.getItem('cancersystem_menubutton'),
    selectedOrgId: '',
    // 视图的显示状态
    editViewVisible: false,
    // CasUserList视图的显示状态
    casUserListViewVisible: false,
    record: {},
    isAddOrEdit: '',
    userId: '',
    columns: [],
    // 待完善个数
    dws: 0,
  };

  getColumns = () => {
    const columns = [
      {
        title: formatMessage({ id: 'app.sysuser.username' }),
        copyable: true,
        dataIndex: 'username',
      },
      {
        title: formatMessage({ id: 'app.settings.basic.nickname' }),
        dataIndex: 'nickname',
      },
      {
        title: formatMessage({ id: 'app.sysuser.mobile' }),
        dataIndex: 'mobile',
      },
      {
        title: formatMessage({ id: 'app.sysuser.roleid' }),
        dataIndex: 'roleIdCn',
      },
      {
        title: formatMessage({ id: 'app.sysuser.orgid' }),
        dataIndex: 'orgIdCn',
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 120,
        render: (text, record, index) => {
          const { id, status } = record;
          /** 改变用户状态 */
          const changStatus = () => {
            const { dispatch } = this.props;
            dispatch({
              type: 'sysUser/changeStatus',
              payload: {
                id,
                status,
              },
            }).then(resp => {
              if (resp.message == 'success') {
                this.successMessage('操作成功！');
              } else {
                this.successMessage('操作失败！');
              }
            });
          };
          return (
            <Switch
              checkedChildren="正常"
              unCheckedChildren="禁用"
              defaultChecked={status === 1}
              onChange={changStatus}
            />
          );
          // return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },
      {
        title: formatMessage({ id: 'app.common.create-time' }),
        dataIndex: 'createTime',
        // width: '12%',
        width: 200,
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        title: formatMessage({ id: 'app.common.operate' }),
        align: 'center',
        width: 200,
        fixed: 'right',
        render: (text, record) => (
          <Fragment>
            {this.state.hiddenMenuButton.indexOf('sysuser:update') !== -1 ? null : (
              // <a onClick={() => this.handleUpdateModalVisible(true, record)}>
              //   <Icon type="edit" />
              //   {formatMessage({ id: 'app.common.edit' })}
              // </a>
              <a onClick={() => this.handleUpdateModal(true, record, record.id)}>
                <Icon type="edit" />
                {formatMessage({ id: 'app.common.edit' })}
              </a>
            )}
            <Divider type="vertical" />
            <Popconfirm
              title={formatMessage({ id: 'app.common.confirm-delete' })}
              onConfirm={() => this.deleteItem(record.id)}
            >
              {this.state.hiddenMenuButton.indexOf('sysuser:delete') !== -1 ? null : (
                <a>
                  <Icon type="delete" />
                  {formatMessage({ id: 'app.common.delete' })}
                </a>
              )}
            </Popconfirm>
          </Fragment>
        ),
      },
    ];
    this.setState({
      columns,
    });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/fetch',
    });
    dispatch({
      type: 'sysUser/fetchRole',
    });
    dispatch({
      type: 'sysUser/fetchOrgTree',
    }).then(resp => {
      const { data, success } = resp;
      if (success) {
        this.setState({
          orgData: data.list,
        });
      }
    });
    this.queryAllUnInitSysuserCount();
    this.getColumns();
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'sysUser/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    this.setState({
      selectedOrgId: '',
    });
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'sysUser/fetch',
      payload: {},
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/delete',
      payload: {
        id,
      },
    }).then(response => {
      if (response.message == 'success') {
        this.setState({
          selectedRows: [],
        });
        message.success(formatMessage({ id: 'app.common.delete-success' }));
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysUser/fetch',
        payload: {},
      });
    });
  };

  handleDeleteClick = () => {
    const { selectedRows } = this.state;

    if (selectedRows.length === 0) {
      message.warning(formatMessage({ id: 'app.common.choose-delete' }));
      return;
    }

    Modal.confirm({
      title: formatMessage({ id: 'app.common.batch-delete' }),
      content: formatMessage({ id: 'app.common.confirm-batch-delete' }),
      okText: formatMessage({ id: 'app.common.confirm' }),
      cancelText: formatMessage({ id: 'app.common.cancel' }),
      onOk: () => this.deleteItem(selectedRows.map(row => row.id)),
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    if (e) {
      e.preventDefault();
    }
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });
      const { username, status } = values;
      const orgId = this.state.selectedOrgId;
      if (orgId !== '' && orgId !== null) {
        dispatch({
          type: 'sysUser/getUserByOrgId',
          payload: {
            username,
            status,
            orgId,
          },
        });
      } else {
        dispatch({
          type: 'sysUser/getUserByOrgId',
          payload: {
            username,
            status,
          },
        });
      }

      // dispatch({
      //   type: 'sysUser/fetch',
      //   payload: { values },
      // });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      updateFormValues: record || {},
    });
  };

  /** 打开编辑视图 */
  handleUpdateModal = (flag, record, userId) => {
    const { id } = record;
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/getUserById',
      payload: {
        userId: id,
      },
    }).then(response => {
      const {
        success,
        data: { sysUser },
      } = response;
      if (success) {
        this.setState({
          editViewVisible: success,
          title: '编辑',
          record: sysUser || {},
          isAddOrEdit: false,
          userId,
        });
      }
    });
  };

  handleExport = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'sysUser/export',
        payload: values,
      }).then(response => {
        saveAs(response, `${formatMessage({ id: 'app.sysuser.user-manage' })  }.xlsx`);
        dispatch({
          type: 'sysUser/fetch',
          payload: values,
        });
      });
    });
  };

  handleAdd = fields => {
    // 进行密码设置的验证
    const { password } = fields;
    const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])[a-zA-Z\d\W_]{8,}$/;
    if (!reg.test(password)) {
      this.errorMessage('密码必须8位以上,包含大小写字母,数字特殊符号');
      return;
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/add',
      payload: {
        username: fields.username,
        nickname: fields.nickname,
        password: fields.password,
        email: fields.email,
        mobile: fields.mobile,
        roleId: [fields.roleId],
        orgId: fields.orgId,
        status: fields.status,
        departmentName: fields.departmentName,
        gender: fields.gender,
        job: fields.job,
        jobTitle: fields.jobTitle,
        postalAddress: fields.postalAddress,
        profession: fields.profession,
        postalCode: fields.postalCode,
      },
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.add-success' }));
        this.handleModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysUser/fetch',
        payload: {},
      });
    });
  };

  handleEditUser = fields => {
    const { dispatch } = this.props;
    const { userId } = this.state;
    const hide = this.loadingMessage('正在更新,请稍后...');
    dispatch({
      type: 'sysUser/update',
      payload: {
        body: {
          id: userId,
          username: fields.username,
          nickname: fields.nickname,
          password: fields.password,
          email: fields.email,
          ndaUrl: fields.ndaUrl,
          mobile: fields.mobile,
          roleId: [fields.roleId],
          orgId: fields.orgId,
          status: fields.status,
          departmentName: fields.departmentName,
          gender: fields.gender,
          job: fields.job,
          jobTitle: fields.jobTitle,
          postalAddress: fields.postalAddress,
          profession: fields.profession,
          postalCode: fields.postalCode,
        },
      },
    })
      .then(response => {
        hide();
        const { success, message } = response;
        if (success) {
          this.setState(
            {
              editViewVisible: false,
            },
            () => {
              this.successMessage(message);
              dispatch({
                type: 'sysUser/fetch',
                payload: {},
              });
            }
          );
        } else if (message.indexOf('|') > -1) {
            const messages = message.split('|').map((item, index) => {
              return <div key={index}>{item}</div>;
            });
            this.errorMessage(messages);
          } else {
            this.errorMessage(message);
          }
      })
      .catch(reason => {
        hide();
      });
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/update',
      payload: {
        body: {
          username: fields.username,
          nickname: fields.nickname,
          password: fields.password,
          email: fields.email,
          mobile: fields.mobile,
          roleId: [fields.roleId],
          orgId: fields.orgId,
          status: fields.status,
          prefix: fields.prefix,
          id: fields.id,
        },
      },
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.edit-success' }));
        this.handleUpdateModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysUser/fetch',
        payload: {},
      });
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label={formatMessage({ id: 'app.sysuser.username' })}>
              {getFieldDecorator('username')(
                <Input placeholder={formatMessage({ id: 'app.common.enter' })} />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label={formatMessage({ id: 'app.sysuser.status' })}>
              {getFieldDecorator('status')(
                <Select
                  placeholder={formatMessage({ id: 'app.common.choose' })}
                  style={{ width: '100%' }}
                >
                  <Option value="1">{formatMessage({ id: 'app.common.able' })}</Option>
                  <Option value="0">{formatMessage({ id: 'app.common.disable' })}</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" icon="search">
                {formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                onClick={this.handleFormReset}
                type="primary"
                icon="reload"
              >
                {formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      sysUser: { data, roleSelectData },
      loading,
    } = this.props;
    const { orgData } = this.state;
    let roleData;
    if ({ roleSelectData }.roleSelectData) {
      roleData = { roleSelectData }.roleSelectData;
    }

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.handleSelectRows(selectedRows);
      },
    };
    return (
      <div>
        <Row>
          <Col span={5}>
            <Card bordered={false} style={{ marginRight: '24px', minHeight: '750px' }}>
              {this.props.isLoadingLeftTree ? (
                <LeftLoadingBox>
                  <Spin />
                </LeftLoadingBox>
              ) : orgData.length > 0 ? (
                <Tree
                  showLine
                  defaultExpandedKeys={['100']}
                  onSelect={this.handleTreeNodeSelect}
                  style={{ fontSize: '11px' }}
                >
                  {this.renderTreeNodes(orgData)}
                </Tree>
              ) : (
                <></>
              )}
            </Card>
          </Col>
          <Col span={19}>
            <Card bordered={false} style={{ minHeight: '750px' }}>
              <div className={styles.tableList}>
                <div className={styles.tableListForm}>{this.renderForm()}</div>
                <div className={styles.tableListOperator}>
                  {/* {this.state.hiddenMenuButton.indexOf('sysuser:add') !== -1 ? null : (
                    <Button icon="plus" type="primary" onClick={this.onClickOpen}>
                      {formatMessage({ id: 'app.common.add' })}
                    </Button>
                  )} */}
                  {this.state.hiddenMenuButton.indexOf('sysuser:export') !== -1 ? null : (
                    <Button icon="file-excel" type="primary" onClick={this.handleExport}>
                      {formatMessage({ id: 'app.common.export' })}
                    </Button>
                  )}
                  {this.state.hiddenMenuButton.indexOf('sysuser:delete') !== -1 ? null : (
                    <Button icon="delete" type="danger" ghost onClick={this.handleDeleteClick}>
                      {formatMessage({ id: 'app.common.batch-delete' })}
                    </Button>
                  )}
                  {/* 待完善数据 */}
                  <Badge count={this.state.dws} offset={[-8, 0]}>
                    <Button icon="warning" type="default" onClick={this.handleDwsBtnClick}>
                      待完善账号
                    </Button>
                  </Badge>
                </div>
                <ProTable
                  bordered
                  search={false}
                  rowKey={record => record.id}
                  rowSelection={rowSelection}
                  loading={loading}
                  dataSource={data ? data.list : []}
                  pagination={data ? data.pagination : {}}
                  columns={this.state.columns}
                  onChange={this.handleBasicTableChange}
                  scroll={{ x: true }}
                  options={{
                    density: true,
                    reload: () => {
                      this.handleSearch();
                    },
                    fullScreen: true,
                    setting: true,
                  }}
                  size="small"
                  style={{marginTop:'20px'}}
                />
              </div>
            </Card>
          </Col>
        </Row>
        {/* 编辑用户信息 */}
        {this.state.editViewVisible ? (
          <AddOrEditView
            isAddOrEdit={this.state.isAddOrEdit}
            record={this.state.record}
            roleData={roleData}
            title={this.state.title}
            orgData={orgData}
            onClose={this.handleEditViewClose}
            visible={this.state.editViewVisible}
            onSubmit={this.handleEditViewSubmit}
            onEdit={this.handleEdit}
          />
        ) : null}
        {/* 未同步列表 */}
        {this.state.casUserListViewVisible ? (
          <CasUserList
            onClose={this.handleCasUserListClose}
            visible={this.state.casUserListViewVisible}
            title="待同步账号列表"
            roleData={roleData}
            orgData={orgData}
          />
        ) : null}
      </div>
    );
  }

  /**
   * 编辑视图关闭
   */
  handleEditViewClose = () => {
    this.setState({
      editViewVisible: false,
    });
  };

  handleEditViewSubmit = data => {
    this.handleAdd(data);
    this.setState({
      editViewVisible: false,
    });
  };

  onClickOpen = () => {
    this.setState({
      editViewVisible: true,
      isAddOrEdit: true,
      title: '新增',
    });
  };

  /** 编辑保存用户信息 */
  handleEdit = data => {
    this.handleEditUser(data);
  };

  /**
   * 渲染树节点
   * @param data
   * @returns {*}
   */
  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} dataRef={item} />;
    });

  /**
   * 树节点点击事件
   * @param selectedKeys
   * @param e
   */
  handleTreeNodeSelect = (selectedKeys, e) => {
    const orgId = selectedKeys[0];
    this.setState({
      selectedOrgId: orgId,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/getUserByOrgId',
      payload: {
        orgId,
        currentPage: 1,
        pageSize: 10,
      },
    });
    // 查找该节点下的所有用户
  };

  /**
   * 待完善按钮被点击
   */
  handleDwsBtnClick = () => {
    const { dws } = this.state;
    if (dws === 0) {
      this.errorMessage('暂无待完善账号');
    } else {
      // 代开待完善账号列表页面
      console.log('代开待完善账号列表页面');
      this.setState({
        casUserListViewVisible: true,
      });
    }
  };

  /**
   * 查询待完善账号数量
   */
  queryAllUnInitSysuserCount = () => {
    this.execHttp('systeminit/queryAllUnInitSysuserCount', {})
      .then(resp => {
        const { success, data } = resp;
        if (success) {
          this.setState({
            dws: data.count,
          });
        }
      })
      .catch(err => {});
  };

  handleCasUserListClose = () => {
    this.setState(
      {
        casUserListViewVisible: false,
      },
      () => {
        this.queryAllUnInitSysuserCount();
      }
    );
  };
}

export default UserSetting;
